package day7;

public class Trie {

    static class TreeNode{
        boolean val;
        TreeNode[] children = new TreeNode[26];
    }

    TreeNode root;

    public Trie() {
        root = new TreeNode();
    }

    public void insert(String word) {
        TreeNode node = root;
        for (int i = 0; i<word.length(); i++) {
            int num = word.charAt(i)-'a';
            node.children[num] = new TreeNode();
            node = node.children[num];
        }
        node.val = true;
    }

    public boolean search(String word) {
        TreeNode node = root;
        for (int i = 0; i<word.length(); i++) {
            int num = word.charAt(i)-'a';
            if(node.children[num]==null) return false;
            node = node.children[num];
        }
        return node.val;
    }

    public boolean startsWith(String prefix) {
        TreeNode node = root;
        for (int i = 0; i<prefix.length(); i++) {
            int num = prefix.charAt(i)-'a';
            if(node.children[num]==null) return false;
            node = node.children[num];
        }
        return true;


    }


}